#include "Commonfunction.h"

int asServer(string name, int port_number) {
	struct hostent *ptrh; /* pointer to a host table entry       */
	struct protoent *ptrp; /* pointer to a protocol table entry   */
	struct sockaddr_in sad; /* structure to hold server's address  */
	int sd; /* socket descriptors                  */
	int port; /* protocol port number                */
	size_t alen; /* length of address        	        */
	char buf[1000]; /* buffer for string the server sends  */

	memset((char *) &sad, 0, sizeof(sad)); /* clear sockaddr structure */
	sad.sin_family = AF_INET; /* set family to Internet     */
	sad.sin_addr.s_addr = INADDR_ANY; /* set the local IP address   */

	port = port_number;
	//	cout << name << ':' << port << endl;

	sad.sin_port = htons((u_short) port_number);

	/* Map TCP transport protocol name to protocol number */
	if (((int) (ptrp = getprotobyname("tcp"))) == 0) {
		cerr << "cannot map \"tcp\" to protocol number" << endl;
		return -1;
	}

	/* Create a socket */
	sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
	if (sd < 0) {
		cerr << "socket creation failed" << endl;
		return -2;
	}

	/* Bind a local address to the socket */
	if (bind(sd, (struct sockaddr *) &sad, sizeof(sad)) < 0) {
		cerr << "bind failed" << endl;
		return -3;
	}
	return sd;
}

int asClient(string name, char* ip, int server_port) {
	int csport;
	int local_server_port;
	int sockfd, numbytes;
	char buf[MAXDATASIZE];
	struct hostent *he;
	struct sockaddr_in their_addr;
	char argv[15];
	char *host; /* pointer to host name      */
	int n; /* number of characters read */

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		cerr << name << ":" << "Fail to create socket" << endl;
		return -1;
	}

	their_addr.sin_family = AF_INET;
	their_addr.sin_port = htons((u_short) server_port);
	if (inet_aton(ip, &their_addr.sin_addr) == 0) {
		cerr << name << ":" << "IP format error";
		return -2;
	}

	bzero(&(their_addr.sin_zero), 8);

	if (connect(sockfd, (struct sockaddr *) &their_addr,
			sizeof(struct sockaddr)) == -1) {
		cerr << name << ":" << "Fail to connect server" << endl;
		return -3;
	}

	if ((numbytes = recv(sockfd, buf, MAXDATASIZE, 0)) == -1) {
		cerr << name << ":" << "Server connect test fail" << endl;
		return -4;
	}

	buf[numbytes] = '\0';
	//cout << name << ":" << buf << ": You can send message to the server now!" << endl;

	return sockfd;
}

